<template>
  <div style="border: 1px solid #ccc;">
    <div id="editor-container" class="text"></div>
  </div>
</template>
<script>
import load from '../dynamicLoadScript'
import { upload } from '@/api/manage'

const CDN = 'https://static.gz640.cn/wangeditor/wangEditor-4.7.min.js'

export default {
  components: {
  },
  props: {
    mode: {
      type: String,
      default: 'simple'
    },
    height: {
      type: Number,
      default: 650
    },
    source: {
      type: String,
      default: 'ARTICLE'
    }
  },
  data () {
    return {
      editorId: `w-e-${Math.random().toString().slice(-5)}`,
      toolbarConfig: {},
      editor: null
    }
  },
  methods: {
    getContent () {
      return this.editor.txt.html()
    },
    setContent (html) {
      if (this.editor) {
        this.editor.txt.html(html)
      } else {
        setTimeout(() => {
          if (this.editor) {
            this.editor.txt.html(html)
          } else {
            setTimeout(() => {
              this.editor.txt.html(html)
            }, 400)
          }
        }, 300)
      }
    },
    createEditor () {
      if (!document.getElementById('editor-container')) {
        return
      }
      const E = window.wangEditor
      this.editor = new E('#editor-container')
      this.editor.config.height = this.height
      const that = this
      this.editor.config.customUploadImg = function (resultFiles, insertImgFn) {
        console.log(resultFiles)
        const form = new FormData()
        form.append('file', resultFiles[0])
        form.append('source', that.source)
        form.append('code', '')
        upload(form).then(res => {
          insertImgFn(res.data.previewUrl)
        })
      }
      this.editor.create()
    }
  },
  beforeDestroy () {
    if (this.editor == null) return
    // 【注意】组件销毁时，及时销毁编辑器
    this.editor.destroy()
  },
  created () {
    load(CDN)
  },
  mounted () {
    console.log(window.wangEditor)
    if (window.wangEditor) {
      this.createEditor()
    } else {
      setTimeout(() => {
        if (window.wangEditor) {
          this.createEditor()
        } else {
          setTimeout(() => {
            this.createEditor()
          }, 500)
        }
      }, 400)
    }
  }
}
</script>
<style lang="less">
.w-e-toolbar>.w-e-menu>i{
  color: #444343 !important;
}
#editor-container{
  >.w-e-toolbar{
    z-index: 20 !important;
  }
  >.w-e-text-container{
    z-index: 10 !important;
  }
}
pre{
  background: #444343;
  color: #fff;
  code{
    background: #444343 !important;
    color: #fff;
  }
}
</style>
